<template>
  <div class="page-container">
    <div ref="chart" class="container-charts"></div>
  </div>
</template>

<script>
import { cropAreasProportion } from "../request/api";
export default {
  data(){
     return {
      info: null,
    };
  },
   computed: {
    changeTheme() {
      return this.$store.state.theme;
    },
  },
  watch: {
    //监听计算属性
    changeTheme() {
      //销毁整个图表实例
      this.info.dispose()
      this.init();
      this.getData();
      //页面一加载调用自适应函数
      this.screen();
    },
  },
  mounted() {
    this.init();
    this.getData();
    this.screen();
    window.addEventListener("resize", this.screen);
  },
  // 销毁
  destroyed() {
    window.removeEventListener("resize", this.screen);
  },
  methods: {
    init() {
      //  查找图表节点
      let chart = this.$refs.chart;

      //初始化 echart
      let myChart = this.$echart.init(chart);
      this.info = myChart;
      // 定义配置项
      let options = {
        title: {
          text: "主要地区农作物种植区域占比",
          left: 10,
          top: 5,
        },
      };
      // 给echart设置配置项
      myChart.setOption(options);
    },
    // 获取数据
    async getData() {
      // 调用接口
      let result = await cropAreasProportion();
      // 定义中心坐标
      let centerList = [
        ["12%", "60%"],
        ["37%", "60%"],
        ["62%", "60%"],
        ["87%", "60%"],
      ];
      // 定义数据列表
      let seriesData = result.data.map((item, index) => {
        return {
          type: "pie", // 饼图
          center: centerList[index],
          label: {
            show: true,
            position: "center",
          },
          data: [
            {
              name: item.areas + "\n" + item.zb + "%",
              value: item.zb,
            },
            {
              value: item.other,
            },
          ],
        };
      });
      this.setEchart(seriesData);
    },
    // 重置设置
    setEchart(seriesData) {
      let options = {
        series: seriesData,
      };
      this.info.setOption(options);
    },
    // 自适应
    screen() {
      // 图表自适应
      this.info.resize();
      // 标题字体的自适应
      let width = this.$refs.chart.offsetWidth;
      let num = (width / 100) * 3;
      // 设置半径的自适应算法
      let innerRadius = num * 1.6;
      // 设置外半径自适应算法
      let outerRadius = num * 1.2;
      let seriesData = [1, 2, 3, 4].map((item) => {
        return {
          type: "pie",
          radius: [innerRadius, outerRadius],
          label: {
            fontSize: num * 0.7, //环形内部字体大小号的计算
          },
        };
      });
      // 重置设置字体
      let options = {
        title: {
          textStyle: {
            fontSize: num,
          },
        },
        series: seriesData,
      };
      this.info.setOption(options);
    },
  },
};
</script>

<style>
</style>